const WebSocket = require('ws');

class WebSocketServer {
  constructor() {
    this.wss = null;
  }

  // 初始化 WebSocket 服务器
  initialize(server) {
    this.wss = new WebSocket.Server({ server });

    // WebSocket 连接处理
    this.wss.on('connection', (ws) => {
      console.log('新的 WebSocket 连接');
      ws.on('error', console.error);
    });
  }

  // 广播书籍状态变化
  broadcastBookStatus(bookId, status, isDelete = false) {
    if (!this.wss) return;

    this.wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify({
          type: 'book_status_change',
          data: {
            bookId,
            status,
            isDelete
          }
        }));
      }
    });
  }

  // 广播新书籍发布
  broadcastNewBook(bookData) {
    if (!this.wss) return;

    this.wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify({
          type: 'new_book_published',
          data: bookData
        }));
      }
    });
  }

  // 广播书籍更新
  broadcastBookUpdate(bookData) {
    if (!this.wss) return;

    this.wss.clients.forEach((client) => {
      if (client.readyState === WebSocket.OPEN) {
        client.send(JSON.stringify({
          type: 'book_updated',
          data: bookData
        }));
      }
    });
  }
}

// 导出单例
module.exports = new WebSocketServer();